// 用户基本资料模块API接口

/**
 * 用户模块API
 * @param {Object} config - API配置信息
 * @returns {Object} - 用户相关API方法集合
 */
module.exports = function(config) {
  // 获取用户相关的API路径
  const userPaths = config.paths.user;
  
  return {
    /**
     * 获取当前用户基本信息
     * @param {string} token - 访问令牌
     * @returns {Promise} - 用户信息
     */
    getProfile: (token) => {
      return new Promise((resolve, reject) => {
        wx.request({
          url: config.getFullUrl(userPaths.profile),
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data.code === 200) {
              resolve(res.data.data);
            } else {
              reject(res.data);
            }
          },
          fail: reject
        });
      });
    },
    
    /**
     * 更新用户基本信息
     * @param {string} token - 访问令牌
     * @param {Object} data - 要更新的用户信息
     * @param {string} data.nickname - 昵称(可选)
     * @param {string} data.gender - 性别(可选，'M'-男, 'F'-女, 'O'-其他)
     * @param {string} data.email - 电子邮箱(可选)
     * @param {string} data.phone - 联系电话(可选)
     * @returns {Promise} - 更新结果
     */
    updateProfile: (token, data) => {
      return new Promise((resolve, reject) => {
        // 确保性别值在有效范围内
        if (data.gender && !['M', 'F', 'O'].includes(data.gender)) {
          reject({
            code: 400,
            message: '性别值无效，必须是 M(男)、F(女) 或 O(其他)'
          });
          return;
        }
        
        wx.request({
          url: config.getFullUrl(userPaths.profile),
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${token}`
          },
          data,
          success: (res) => {
            if (res.data.code === 200) {
              resolve(res.data.data);
            } else {
              reject(res.data);
            }
          },
          fail: reject
        });
      });
    },
    
    /**
     * 更新用户头像
     * @param {string} token - 访问令牌
     * @param {string} filePath - 本地文件路径
     * @returns {Promise} - 上传结果
     */
    updateAvatar: (token, filePath) => {
      return new Promise((resolve, reject) => {
        console.log('开始上传头像到API:', config.getFullUrl(userPaths.avatar));
        console.log('文件路径:', filePath);
        
        wx.uploadFile({
          url: config.getFullUrl(userPaths.avatar),
          filePath,
          name: 'avatar',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            console.log('上传头像响应:', res);
            try {
              const data = JSON.parse(res.data);
              if (data.code === 200) {
                // 按照API文档中的响应格式解析数据
                const avatarData = {
                  avatar: data.data.avatar || data.data.url,
                  objectPath: data.data.objectPath,
                  updatedAt: data.data.updatedAt
                };
                console.log('头像上传成功:', avatarData);
                resolve(avatarData);
              } else {
                console.error('头像上传失败, 服务器返回错误:', data);
                if (data.code === 400) {
                  reject({
                    code: 400, 
                    message: '文件格式不正确或文件过大',
                    error: data
                  });
                } else {
                  reject(data);
                }
              }
            } catch (e) {
              console.error('解析服务器响应失败:', e, '原始响应:', res.data);
              reject({
                code: 500,
                message: '服务器响应解析失败',
                error: e,
                rawData: res.data
              });
            }
          },
          fail: (err) => {
            console.error('头像上传请求失败:', err);
            reject(err);
          }
        });
      });
    },
    
    /**
     * 获取指定用户详细资料
     * @param {string} token - 访问令牌
     * @param {number|string} userId - 用户ID
     * @returns {Promise} - 用户信息
     */
    getUserProfile: (token, userId) => {
      return new Promise((resolve, reject) => {
        wx.request({
          url: config.getFullUrl(userPaths.profileById(userId)),
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data.code === 200) {
              resolve(res.data.data);
            } else {
              reject(res.data);
            }
          },
          fail: reject
        });
      });
    },
    
    /**
     * 获取当前用户学生详细资料
     * @param {string} token - 访问令牌
     * @returns {Promise} - 学生资料
     */
    getStudentProfile: (token) => {
      return new Promise((resolve, reject) => {
        console.log('开始获取学生档案信息');
        
        // 首先尝试使用student-profile接口
        wx.request({
          url: config.getFullUrl(userPaths.studentProfile),
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.data.code === 200) {
              console.log('学生档案信息获取成功:', res.data.data);
              resolve(res.data.data);
            } else if (res.statusCode === 404 || res.data.code === 404) {
              console.log('student-profile接口不存在，尝试从常规profile获取');
              
              // 如果student-profile接口不存在，尝试从常规profile中获取studentProfile字段
              wx.request({
                url: config.getFullUrl(userPaths.profile),
                method: 'GET',
                header: {
                  'Authorization': `Bearer ${token}`
                },
                success: (profileRes) => {
                  if (profileRes.data.code === 200 && profileRes.data.data) {
                    // 检查profile中是否包含studentProfile字段
                    const profile = profileRes.data.data;
                    if (profile.studentProfile) {
                      console.log('从profile中获取到学生资料:', profile.studentProfile);
                      resolve(profile.studentProfile);
                    } else {
                      console.log('profile中没有学生资料信息，创建新的学生资料');
                      // 创建新的学生资料
                      const newStudentProfile = {
                        user_id: profile.id,
                        real_name: '',
                        gender: '',
                        birth_date: '',
                        id_card: '',
                        nationality: '',
                        native_place: '',
                        political_status: '',
                        marital_status: '',
                        education_level: '',
                        school: '',
                        school_level: '',
                        major: '',
                        major_category: '',
                        enrollment_year: '',
                        expected_graduation: '',
                        is_graduated: false,
                        gpa: '',
                        gpa_ranking: '',
                        academic_achievements: '',
                        course_scores: '',
                        skills: [],
                        skill_levels: [],
                        languages: [],
                        language_certs: [],
                        technical_certs: [],
                        professional_certs: [],
                        internship_experience: [],
                        part_time_jobs: [],
                        project_experience: [],
                        campus_activities: [],
                        volunteer_experience: [],
                        awards: [],
                        competitions: [],
                        ability_scores: {},
                        personal_strengths: '',
                        personal_weaknesses: '',
                        career_goals: '',
                        self_evaluation: '',
                        intended_industries: [],
                        intended_companies: [],
                        intended_positions: [],
                        expected_salary: '',
                        expected_locations: [],
                        job_status: '',
                        available_date: '',
                        willing_to_relocate: false,
                        willing_to_travel: false,
                        work_hours_preference: ''
                      };
                      
                      // 更新学生资料
                      wx.request({
                        url: config.getFullUrl(userPaths.studentProfile),
                        method: 'PUT',
                        header: {
                          'Authorization': `Bearer ${token}`,
                          'Content-Type': 'application/json'
                        },
                        data: newStudentProfile,
                        success: (updateRes) => {
                          if (updateRes.data.code === 200) {
                            console.log('新学生资料创建成功:', updateRes.data.data);
                            resolve(updateRes.data.data);
                          } else {
                            console.error('创建新学生资料失败:', updateRes.data);
                            resolve(newStudentProfile); // 返回默认值
                          }
                        },
                        fail: (updateErr) => {
                          console.error('创建新学生资料请求失败:', updateErr);
                          resolve(newStudentProfile); // 返回默认值
                        }
                      });
                    }
                  } else {
                    console.error('获取profile失败:', profileRes.data);
                    resolve(null); // 返回null而不是拒绝Promise
                  }
                },
                fail: (profileErr) => {
                  console.error('获取profile请求失败:', profileErr);
                  reject(profileErr);
                }
              });
            } else {
              console.error('获取学生档案信息失败:', res.data);
              reject(res.data);
            }
          },
          fail: (err) => {
            console.error('获取学生档案信息请求失败:', err);
            reject(err);
          }
        });
      });
    },
    
    /**
     * 更新当前用户学生详细资料
     * @param {string} token - 访问令牌
     * @param {Object} data - 要更新的学生信息
     * @returns {Promise} - 更新结果
     */
    updateStudentProfile: (token, data) => {
      console.log('学生资料更新请求，尝试使用student-profile接口', data);
      
      // 确保婚姻状况使用正确的英文值格式
      if (data.marital_status) {
        const validMaritalStatuses = ['Single', 'Married', 'Divorced', 'Widowed'];
        
        if (!validMaritalStatuses.includes(data.marital_status)) {
          // 如果是中文值，则尝试转换为英文值
          const maritalStatusMap = {
            '未婚': 'Single',
            '已婚': 'Married',
            '离异': 'Divorced',
            '丧偶': 'Widowed',
            'UNMARRIED': 'Single',
            'MARRIED': 'Married',
            'DIVORCED': 'Divorced',
            'WIDOWED': 'Widowed'
          };
          
          data.marital_status = maritalStatusMap[data.marital_status] || 'Single';
        }
        
        console.log('[API] 校正后的婚姻状况:', data.marital_status);
      }
      
      // 确保删除不存在的字段
      if (data.hasOwnProperty('ethnic')) {
        delete data.ethnic;
      }
      
      // 构建profileData对象，包含常规和学生资料字段
      const profileData = {
        // 常规资料字段
        nick_name: data.nick_name,
        avatar_url: data.avatar_url,
        // 学生资料字段，只保留与数据库表结构匹配的字段
        real_name: data.real_name,
        gender: data.gender,
        birth_date: data.birth_date,
        id_card: data.id_card,
        nationality: data.nationality,
        native_place: data.native_place,
        political_status: data.political_status,
        marital_status: data.marital_status,
        education_level: data.education_level,
        school: data.school,
        school_level: data.school_level,
        major: data.major,
        major_category: data.major_category,
        enrollment_year: data.enrollment_year,
        expected_graduation: data.expected_graduation,
        is_graduated: data.is_graduated,
        gpa: data.gpa,
        gpa_ranking: data.gpa_ranking,
        academic_achievements: data.academic_achievements,
        course_scores: data.course_scores,
        // 学生表中的其他字段
        skills: data.skills,
        skill_levels: data.skill_levels,
        languages: data.languages,
        language_certs: data.language_certs,
        technical_certs: data.technical_certs,
        professional_certs: data.professional_certs,
        internship_experience: data.internship_experience,
        part_time_jobs: data.part_time_jobs,
        project_experience: data.project_experience,
        campus_activities: data.campus_activities,
        volunteer_experience: data.volunteer_experience,
        awards: data.awards,
        competitions: data.competitions,
        ability_scores: data.ability_scores,
        personal_strengths: data.personal_strengths,
        personal_weaknesses: data.personal_weaknesses,
        career_goals: data.career_goals,
        self_evaluation: data.self_evaluation,
        intended_industries: data.intended_industries,
        intended_companies: data.intended_companies,
        intended_positions: data.intended_positions,
        expected_salary: data.expected_salary,
        expected_locations: data.expected_locations,
        job_status: data.job_status,
        available_date: data.available_date,
        willing_to_relocate: data.willing_to_relocate,
        willing_to_travel: data.willing_to_travel,
        work_hours_preference: data.work_hours_preference
      };
      
      return new Promise((resolve, reject) => {
        // 首先尝试使用student-profile接口
        wx.request({
          url: config.getFullUrl(userPaths.studentProfile),
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: data,
          success: (res) => {
            if (res.data.code === 200) {
              console.log('学生资料更新成功(student-profile接口):', res.data);
              resolve(res.data.data);
            } else if (res.statusCode === 404 || res.data.code === 404) {
              console.log('student-profile接口不存在，尝试使用profile接口');
              
              // 如果student-profile接口不存在，则尝试使用profile接口
              wx.request({
                url: config.getFullUrl(userPaths.profile),
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: profileData,
                success: (profileRes) => {
                  if (profileRes.data.code === 200) {
                    console.log('学生资料更新成功(profile接口):', profileRes.data);
                    resolve(profileRes.data.data);
                  } else {
                    console.error('学生资料更新失败(profile接口):', profileRes.data);
                    reject(profileRes.data);
                  }
                },
                fail: (profileErr) => {
                  console.error('学生资料更新请求失败(profile接口):', profileErr);
                  reject(profileErr);
                }
              });
            } else {
              console.error('学生资料更新失败(student-profile接口):', res.data);
              reject(res.data);
            }
          },
          fail: (err) => {
            console.error('学生资料更新请求失败(student-profile接口):', err);
            
            // 请求失败，也尝试使用profile接口
            console.log('尝试使用profile接口作为备选');
            wx.request({
              url: config.getFullUrl(userPaths.profile),
              method: 'PUT',
              header: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              },
              data: profileData,
              success: (profileRes) => {
                if (profileRes.data.code === 200) {
                  console.log('学生资料更新成功(profile接口):', profileRes.data);
                  resolve(profileRes.data.data);
                } else {
                  console.error('学生资料更新失败(profile接口):', profileRes.data);
                  reject(profileRes.data);
                }
              },
              fail: (profileErr) => {
                console.error('学生资料更新请求失败(profile接口):', profileErr);
                reject(profileErr);
              }
            });
          }
        });
      });
    }
  };
} 